package com.xing.crm.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Mr.L
 * @version V1.0
 * @date 2021年07月21日 17:37
 */
@Component
public class UploadUtils {

	@Autowired
	ImageCompression imageSave;

	public List<String> saveFile(HttpServletRequest request, MultipartFile[] files, String savePath) throws IOException
	{
		/* 获取类路径 */
		String dirPath =  System.getProperty("user.dir") + "/upload/";
		List<String> fileNames = new ArrayList();
		Random random = new Random();
		for (MultipartFile file : files) {
			if ((!file.isEmpty()) && (file.getSize() != 0L))
			{
				String fileName = file.getOriginalFilename();
				/* 避免图片太小，执行过快，文件重名覆盖 */
				String saveName = System.currentTimeMillis() + random.nextInt(100) + fileName.substring(fileName.lastIndexOf("."));
				File f = new File(dirPath , saveName);
				if (!f.exists()) {
					f.getParentFile().mkdirs();
				}
				file.transferTo(f);

				//照片宽度自适应压缩
				saveName = imageSave.thumbnail(f.getAbsolutePath(), f.getAbsolutePath());
				fileNames.add("/upload/" + saveName);
			}
		}
		return fileNames;
	}
}
